<script setup lang="tsx">
import { ref, unref, reactive } from 'vue'
import { ElButton, ElDrawer, ElIcon, ElMessageBox, ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import { Search } from '@/components/Search'
import { useSearch } from '@/hooks/web/useSearch'
import Write from './components/Write.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import {
  contentListApi,
  contentDeleteApi,
  contentCategoryListApi,
  contentUpdateStateApi
} from '@/api/college'
import type { ContentItem, ContentCategoryItem } from '@/api/college/types'
import { ContentPortDict, ArticleStateDict, dictToList } from '@/utils/dict'

const { t } = useI18n()

const { searchRegister, searchMethods } = useSearch()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await contentListApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.list || [],
      total: res.data.total || 0
    }
  },
  fetchDelApi: async () => {
    const res = await contentDeleteApi(unref(ids.value[0]))
    return !!res
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const isDisabled = ref(true)

const categoryList = ref<ContentCategoryItem[]>([])
const getCategoryList = async (contentPort: number) => {
  const res = await contentCategoryListApi({ contentPort: contentPort })
  if (res.code === 200) {
    categoryList.value = res.data.list || []
  }
  searchMethods.setSchema([
    {
      field: 'categoryId',
      path: 'componentProps.options',
      value: unref(
        categoryList.value.map((it: ContentCategoryItem) => ({
          label: it.categoryName,
          value: it.id
        }))
      )
    }
  ])
  searchMethods.setValues({
    categoryId: null
  })
}

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'title',
    label: t('college.articleTitle'),
    form: {
      colProps: {
        span: 24
      },
      componentProps: {
        placeholder: t('college.articleTitleHint')
      }
    }
  },
  {
    field: 'contentPort',
    label: t('college.contentPort'),
    search: {
      component: 'Select',
      componentProps: {
        options: dictToList(ContentPortDict),
        on: {
          change: async (val: number) => {
            if (val) {
              isDisabled.value = false
            } else {
              isDisabled.value = true
            }

            // categoryList.value = []
            console.log('改变', searchParams.value)
            // setSearchParams({
            //   categoryName: null
            // })
            getCategoryList(val)
          }
        }
      }
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as ContentItem
          return (
            <>
              <span>{ContentPortDict[row.contentPort]}</span>
            </>
          )
        }
      }
    }
  },
  {
    // field: 'categoryName',
    field: 'categoryId',
    label: t('college.category'),
    search: {
      // field: 'categoryId',
      label: t('college.articleContentCategory'),
      component: 'Select',
      componentProps: {
        disabled: isDisabled,
        options: []
      }
    },
    table: {
      formatter: ({ categoryName }) => categoryName
    }
  },
  {
    field: 'contentSort',
    label: t('college.articleSort'),
    search: {
      hidden: true
    },
    form: {
      colProps: {
        span: 24
      },
      label: t('college.sortLabel'),
      componentProps: {
        placeholder: t('college.sortHint')
      }
    }
  },
  {
    field: 'contentType',
    label: '内容类型',
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      formatter: ({ contentType }) => (contentType === 1 ? 'URL' : '富文本')
    }
  },
  {
    field: 'state',
    label: t('userDemo.status'),
    form: {
      hidden: true
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dictToList(ArticleStateDict)
      }
    },
    table: {
      formatter: ({ state }) => state && ArticleStateDict[state]
    }
  },
  {
    field: 'createTime',
    label: t('userDemo.createTime'),
    form: {
      hidden: true
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      width: 160,
      slots: {
        default: (data: any) => {
          const row = data.row as ContentItem
          return (
            <>
              <ElButton
                v-hasPermi="POST /content/update"
                type="primary"
                link
                onClick={() => action(row, 'edit')}
              >
                {t('exampleDemo.edit')}
              </ElButton>
              <ElButton
                v-hasPermi="POST /content/updateState"
                type="primary"
                link
                onClick={() => updateState(row)}
              >
                {row.state === 1 ? t('college.down') : t('college.up')}
              </ElButton>
              <ElButton
                v-hasPermi="POST /content/delete"
                type="danger"
                link
                onClick={() => delData(row)}
              >
                {t('exampleDemo.del')}
              </ElButton>
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const searchParams = ref({})
const setSearchParams = (params: any) => {
  const { createTime, ...rest } = params
  let startTime, endTime
  if (createTime && createTime.length > 0) {
    startTime = createTime[0]
    endTime = createTime[1]
  }
  currentPage.value = 1
  if (Object.keys(params).length === 0) {
    isDisabled.value = true
  }
  searchParams.value = {
    startTime,
    endTime,
    ...rest
  }
  getList()
}

const showDrawer = ref(false)
const drawerTitle = ref('')

const currentRow = ref<ContentItem>()

const AddAction = () => {
  drawerTitle.value = t('college.createArticle')
  currentRow.value = undefined
  showDrawer.value = true
}

const action = (row: ContentItem, _type: string) => {
  drawerTitle.value = t('exampleDemo.edit')
  currentRow.value = { ...row }
  showDrawer.value = true
}

const updateState = (row: ContentItem) => {
  const text = row.state === 1 ? t('college.downConfirm') : t('college.upConfirm')
  const success = row.state === 1 ? t('college.downSuccess') : t('college.upSuccess')
  ElMessageBox.confirm(text, {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  })
    .then(() =>
      contentUpdateStateApi({
        id: row.id,
        state: row.state === 1 ? 2 : 1
      })
    )
    .then((res) => {
      if (res.code === 200) {
        ElMessage.success(success)
        getList()
      } else {
        ElMessage.error(res.message)
      }
    })
}

const ids = ref<number[]>([])
const delLoading = ref(false)

const delData = async (row: ContentItem | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: ContentItem) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length, '确认删除此文章？').finally(() => {
    delLoading.value = false
  })
}

const writeRef = ref<ComponentRef<typeof Write>>()
const saveLoading = ref(false)

const save = async () => {
  saveLoading.value = true
  const write = unref(writeRef)
  const res = await write?.submit()
  saveLoading.value = false
  if (!res) {
    return
  }
  showDrawer.value = false
  getList()
}

const onCloseDrawer = () => {
  showDrawer.value = false
  const write = unref(writeRef)
  write?.reset()
}
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="flex-[3] ml-20px">
      <Search
        :schema="allSchemas.searchSchema"
        @reset="setSearchParams"
        @search="setSearchParams"
        @register="searchRegister"
      />

      <div class="mb-10px">
        <ElButton v-hasPermi="'POST /content/save'" type="success" @click="AddAction">
          <ElIcon><Plus /></ElIcon>
          {{ t('college.createArticle') }}
        </ElButton>
      </div>
      <Table
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :columns="allSchemas.tableColumns"
        :data="dataList"
        :loading="loading"
        @register="tableRegister"
        :pagination="{
          total
        }"
      />
    </ContentWrap>
    <ElDrawer
      :title="drawerTitle"
      v-model="showDrawer"
      direction="rtl"
      size="650px"
      @close="onCloseDrawer"
    >
      <Write
        v-if="showDrawer"
        ref="writeRef"
        :form-schema="allSchemas.formSchema"
        :current-row="currentRow"
      />

      <template #footer>
        <ElButton @click="onCloseDrawer">{{ t('common.cancel') }}</ElButton>
        <ElButton type="primary" :loading="saveLoading" @click="save">
          {{ t('exampleDemo.save') }}
        </ElButton>
      </template>
    </ElDrawer>
  </div>
</template>
